;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Enterprise.RatingManager", [])
    .controller("RatingManagerCtrl", ["$scope", "Upload", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$filter", "$q", function ($scope, Upload, ybWidget, ybHttp, MESG_TYPE, UserContextService, $filter, $q) {
        $scope.activeFlag = [true, false, false, false, false];
        $scope.datePickerFlag = [false, false];             // 时间选择器 展示与隐藏
        $scope.exportParam = [];
        $scope.saleCompRateIds = [];
        $scope.saleCompIds = {ids: []};
        $scope.submitted = false;
        // 配置评级规则时间的类型type的枚举值
        var TimeConfigTypeEnum = {
            saleComp: 1,
            monthPlan: 2,
            orderManage: 3,
            allSaleComp: 4
        };

        //销售完成情况，销售完成率配置
        $scope.markInfo = {
            allCheckedSaleComp: false,
            allCheckedSaleCompRate: false,
            curRow: -1
        };
        // 主页的评级规则数据对象
        $scope.mainRatingRulObj = {
            ratingId: '',
            submitted: false,                           // 表单提交状态
            dataList: [],                               // 列表页集合
            detailInfo: {},                             // 详情信息
            condition: {},                              // 搜索条件
            pageInfo: {                                 // 分页信息
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            }
        };

        // 生成评分数据对象
        $scope.viewRateObj = {
            exportUrl: ybHttp.RequestUrl("device", "/scoreInfo/exportAll"),
            dataList: [],                               // 列表页集合
            stepList: { curStep: 0 },                   // 步骤信息
            saleCompEditStatus: false,                  // 销售完成率详情页编辑状态
            monthEditStatus: false,                     // 月度计划详情页编辑状态
            orderEditStatus: false,                     // 订单管理详情页编辑状态
            receiveEditStatus: false,                   // 应收账款详情页编辑状态
            allSaleEditStatus: false,                   // 总体销售完成率详情页编辑状态
            stockEditStatus: false,                     // 库存及业务情页编辑状态
            exportParam: {ids: []},                     // 要导出的参数id数组
            stockDetail: {},                            // 库存及业务得分详情
            allSaleDetail: {},                          // 总体销售得分详情
            receiveDetail: {},                          // 应收账款得分详情
            orderManageDetail: {},                      // 订单管理得分详情
            monthPlanDetail: {},                        // 月度计划得分详情
            saleCompDetail: [],                         // 销售完成率得分详情
            condition: {},                              // 搜索条件
            pageInfo: {                                 // 分页信息
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            }
        };

        // 级别制定数据对象
        $scope.levelMakeObj = {
            ratingId: '',
            firstLevel: {
                activityIdList:[],
            },
            secondLevel: {
                activityIdList:[],
            },
            thirdLevel: {
                activityIdList:[],
            },
            fourthLevel: {
                activityIdList:[],
            },
        };

        // 销售完成情况配置数据对象
        $scope.saleCompObj = {
            dataList: [],                               // 列表页集合
            detailInfo: {},                             // 详情信息
            timeInfo: {},                               // 时间信息
            stepList: { curStep: 0 },                   // 步骤信息
            condition: {},                              // 搜索条件
            pageInfo: {                                 // 分页信息
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            }
        };

        // 月度计划准确性配置数据对象
        $scope.monthPlanObj = {
            timeInfo: {}
        };

        // 订单管理规范性配置数据对象
        $scope.orderManageObj = {
            timeInfo: {}
        };

        // 应收账款逾期配置数据对象
        $scope.receiveCheckObj = {
            dataList: [],                           // 列表页数据集合
            detailInfo: {},                         // 详情信息
            timeInfo: {},                           // 时间配置信息
            stepList: { curStep: 0 },               // 步骤信息
            condition: {},                          // 搜索条件
            pageInfo: {                             // 分页信息
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            }
        };

        // 总体销售完成率配置数据对象
        $scope.allSaleCompObj = {
            dataList: [],                               // 列表页集合
            detailInfo: {},                             // 详情信息
            timeInfo: {},                               // 时间配置信息
            stepList: { curStep: 0 },                   // 步骤信息
            condition: {},                              // 搜索条件
            pageInfo: {                                 // 分页信息
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            }
        };

        // 库存管理及业务规范性加减分数据对象
        $scope.stockAndBusiObj = {
            dataList: [],                               // 列表页集合
            detailInfo: {},                             // 详情信息
            stepList: { curStep: 0 },                   // 步骤信息
            condition: {},                              // 搜索条件
            pageInfo: {                                 // 分页信息
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            }
        };

        $scope.tabFlag = {};
        var tabFlag = ["新增", "编辑"];

        // 评级管理主页表格信息
        $scope.tbConf = {
            fixedWidth: 300,
            scrollWidth: 920,
            tableCol: [
                {
                    type: "",
                    name: "标题",
                    dataField: "title",
                    width: 150,
                    isShow: true,
                },
                {
                    type: "",
                    name: "创建人",
                    dataField: "creatorName",
                    width: 100,
                    isShow: true,
                },
                {
                    type: "",
                    name: "创建时间",
                    dataField: "createTimeStr",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "是否生成评分",
                    dataField: "isScoreStr",
                    width: 100,
                    isShow: true,
                },
                {
                    type: "",
                    name: "备注信息",
                    dataField: "remark",
                    width: 150,
                    isShow: true,
                },
                {
                    type: "operate",
                    name: "操作",
                    dataField: "",
                    width: 300,
                    isShow: true,
                    isFixed: true,
                }
            ]
        };

        // 销售完成情况配置表格信息
        $scope.saleCompleteTb = {
            fixedWidth: 120,
            scrollWidth: 1070,
            tableCol: [
                {
                    type: "",
                    name: "客户",
                    dataField: "clientName",
                    width: 150,
                    isShow: true
                },
                {
                    type: "",
                    name: "油品目标(元)",
                    dataField: "oilTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "滤芯目标(元)",
                    dataField: "filterTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "破碎锤目标(台)",
                    dataField: "brokenHammerTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "斗齿目标(元)",
                    dataField: "toothTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "四轮一带目标(元)",
                    dataField: "fourRoundsTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "液压一带目标(元)",
                    dataField: "hydraulicTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "橡胶件目标(元)",
                    dataField: "rubberPartsTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "operate",
                    name: "操作",
                    dataField: "",
                    width: 80,
                    isShow: true,
                    isFixed: true,
                }
            ]
        };

        // 应收账款逾期配置表格信息
        $scope.receiveCheckTb = {
            fixedWidth: 80,
            scrollWidth: 1590,
            tableCol: [
                {
                    type: "",
                    name: "客户",
                    dataField: "clientName",
                    width: 150,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第一个月回款目标",
                    dataField: "oneReturnTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第一个月实际回款",
                    dataField: "oneActualPayment",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第一个月实账",
                    dataField: "oneRealAccount",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第一个月是否超额完成",
                    dataField: "oneAccountControl",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第二个月回款目标",
                    dataField: "twoReturnTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第二个月实际回款",
                    dataField: "twoActualPayment",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第二个月实账",
                    dataField: "twoRealAccount",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第二个月是否超额完成",
                    dataField: "twoAccountControl",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第三个月回款目标",
                    dataField: "threeReturnTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第三个月实际回款",
                    dataField: "threeActualPayment",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第三个月实账",
                    dataField: "threeRealAccount",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "第三个月是否超额完成",
                    dataField: "threeAccountControl",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "合计扣分",
                    dataField: "score",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "operate",
                    name: "操作",
                    dataField: "",
                    width: 80,
                    isShow: true,
                    isFixed: true,
                }
            ]
        };

        // 总体销售完成率配置表格信息
        $scope.allSaleCompTb = {
            fixedWidth: 120,
            scrollWidth: 500,
            tableCol: [
                {
                    type: "",
                    name: "客户",
                    dataField: "clientName",
                    width: 150,
                    isShow: true,
                },
                {
                    type: "",
                    name: "总体销售目标(元)",
                    dataField: "totalSalesTarget",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "备注",
                    dataField: "remark",
                    width: 150,
                    isShow: true,
                },
                {
                    type: "operate",
                    name: "操作",
                    dataField: "",
                    width: 80,
                    isShow: true,
                    isFixed: true,
                }
            ]
        };

        // 库存管理及业务规范性加减分表格信息
        $scope.stockAndBusiTb = {
            fixedWidth: 80,
            scrollWidth: 800,
            tableCol: [
                {
                    type: "",
                    name: "客户",
                    dataField: "clientName",
                    width: 150,
                    isShow: true,
                },
                {
                    type: "",
                    name: "库存不准确扣分",
                    dataField: "inaccurateDeduction",
                    width: 150,
                    isShow: true,
                },
                {
                    type: "",
                    name: "业务规范加减分",
                    dataField: "businessScore",
                    width: 150,
                    isShow: true,
                },
                {
                    type: "",
                    name: "得分",
                    dataField: "score",
                    width: 120,
                    isShow: true,
                },
                {
                    type: "",
                    name: "备注",
                    dataField: "remark",
                    width: 150,
                    isShow: true,
                },
                {
                    type: "operate",
                    name: "操作",
                    dataField: "",
                    width: 80,
                    isShow: true,
                    isFixed: true,
                }
            ]
        };

        // 查看评分表格信息
        $scope.viewRateTb = {
            scrollWidth: 1190,
            tableCol: [
                {
                    type: "",
                    name: "客户",
                    dataField: "clientName",
                    width: 150,
                    isShow: true,
                },
                {
                    type: "",
                    name: "销售完成情况",
                    dataField: "salesCompletion",
                    width: 120,
                    isShow: true,
                    clickFn: "editSaleComp",
                    toSort: true,
                    sortField: "sales_completion"
                },
                {
                    type: "",
                    name: "月度计划准确性",
                    dataField: "monthPlanAccuracy",
                    width: 120,
                    isShow: true,
                    clickFn: "editMonthPlan",
                    toSort: true,
                    sortField: "month_plan_accuracy"
                },
                {
                    type: "",
                    name: "订单管理规范性",
                    dataField: "orderManagerNormative",
                    width: 120,
                    isShow: true,
                    clickFn: "editOrderManage",
                    toSort: true,
                    sortField: "order_manager_normative"
                },
                {
                    type: "",
                    name: "应收账款逾期",
                    dataField: "accountsOverdue",
                    width: 120,
                    isShow: true,
                    clickFn: "editReceiveCheck",
                    toSort: true,
                    sortField: "accounts_overdue"
                },
                {
                    type: "",
                    name: "总体销售完成率",
                    dataField: "salesCompletionRate",
                    width: 120,
                    isShow: true,
                    clickFn: "editAllSaleComp",
                    toSort: true,
                    sortField: "sales_completion_rate"
                },
                {
                    type: "",
                    name: "库存管理及业务规范性加减分",
                    dataField: "inventoryBusiness",
                    width: 180,
                    isShow: true,
                    clickFn: "editStockAndBusi",
                    toSort: true,
                    sortField: "inventory_business"
                },
                {
                    type: "",
                    name: "总得分",
                    dataField: "totalScore",
                    width: 100,
                    isShow: true,
                    toSort: true,
                    sortField: "total_score"
                },
                {
                    type: "",
                    name: "排名",
                    dataField: "ranking",
                    width: 100,
                    isShow: true,
                    toSort: true,
                    sortField: "ranking"
                },
                {
                    type: "",
                    name: "等级",
                    dataField: "grade",
                    width: 100,
                    isShow: true,
                    toSort: true,
                    sortField: "grade"
                },
            ]
        };

        var btnPermissionCode = {
            ratingEdit: window.ActionCode.ratingEdit,
            ratingAdd: window.ActionCode.ratingAdd,
            ratingDel: window.ActionCode.ratingDel,
            ratingMakeRule: window.ActionCode.ratingMakeRule,
            ratingGenRate: window.ActionCode.ratingGenRate,
            ratingViewRate: window.ActionCode.ratingViewRate,
            ratingMakeLevel: window.ActionCode.ratingMakeLevel,
            ratingSaleCompAdd: window.ActionCode.ratingSaleCompAdd,
            ratingSaleCompEdit: window.ActionCode.ratingSaleCompEdit,
            ratingSaleCompDel: window.ActionCode.ratingSaleCompDel,
            ratingSaleCompTime: window.ActionCode.ratingSaleCompTime,
            ratingSaleCompImp: window.ActionCode.ratingSaleCompImp,
            ratingMonthPlanSave: window.ActionCode.ratingMonthPlanSave,
            ratingOrderManaSave: window.ActionCode.ratingOrderManaSave,
            ratingReceiveEdit: window.ActionCode.ratingReceiveEdit,
            ratingReceiveDel: window.ActionCode.ratingReceiveDel,
            ratingReceiveImp: window.ActionCode.ratingReceiveImp,
            ratingAllSaleAdd: window.ActionCode.ratingAllSaleAdd,
            ratingAllSaleEdit: window.ActionCode.ratingAllSaleEdit,
            ratingAllSaleDel: window.ActionCode.ratingAllSaleDel,
            ratingAllSaleTime: window.ActionCode.ratingAllSaleTime,
            ratingAllSaleImp: window.ActionCode.ratingAllSaleImp,
            ratingStockAdd: window.ActionCode.ratingStockAdd,
            ratingStockEdit: window.ActionCode.ratingStockEdit,
            ratingStockDel: window.ActionCode.ratingStockDel,
            ratingStockImp: window.ActionCode.ratingStockImp,
            ratingGenRank: window.ActionCode.ratingGenRank,
            ratingViewRateExp: window.ActionCode.ratingViewRateExp,
            ratingMakeLevelSave: window.ActionCode.ratingMakeLevelSave,
            ratingViewSaleCompEdit: window.ActionCode.ratingViewSaleCompEdit,
            ratingViewMonthPlanEdit: window.ActionCode.ratingViewMonthPlanEdit,
            ratingViewOrderManaEdit: window.ActionCode.ratingViewOrderManaEdit,
            ratingViewReceiveEdit: window.ActionCode.ratingViewReceiveEdit,
            ratingViewAllSaleEdit: window.ActionCode.ratingViewAllSaleEdit,
            ratingViewStockEdit: window.ActionCode.ratingViewStockEdit,
        };

        $scope.btnPermission = {
            ratingEdit: true,
            ratingAdd: true,
            ratingDel: true,
            ratingMakeRule: true,
            ratingGenRate: true,
            ratingViewRate: true,
            ratingMakeLevel: true,
            ratingSaleCompAdd: true,
            ratingSaleCompEdit: true,
            ratingSaleCompDel: true,
            ratingSaleCompTime: true,
            ratingSaleCompImp: true,
            ratingMonthPlanSave: true,
            ratingOrderManaSave: true,
            ratingReceiveEdit: true,
            ratingReceiveDel: true,
            ratingReceiveImp: true,
            ratingAllSaleAdd: true,
            ratingAllSaleEdit: true,
            ratingAllSaleDel: true,
            ratingAllSaleTime: true,
            ratingAllSaleImp: true,
            ratingStockAdd: true,
            ratingStockEdit: true,
            ratingStockDel: true,
            ratingStockImp: true,
            ratingGenRank: true,
            ratingViewRateExp: true,
            ratingMakeLevelSave: true,
            ratingViewSaleCompEdit: true,
            ratingViewMonthPlanEdit: true,
            ratingViewOrderManaEdit: true,
            ratingViewReceiveEdit: true,
            ratingViewAllSaleEdit: true,
            ratingViewStockEdit: true,
        };

        function setBtnPermission() {
            for (var key in btnPermissionCode) {
                $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
            }
        }

        $scope.setFixedWidth = function () {
            $scope.tbStyle = {
                fixedWidth: {left: $scope.tbConf.fixedWidth + "px"}
            };
        };

        // 切换时间选择器显示与隐藏
        $scope.switchDataPicker = function (index) {
            $scope.datePickerFlag = [false, false];
            if (angular.isDefined(index)) {
                $scope.datePickerFlag[index] = true;
            }
        };

        $scope.changeTab = function (index) {
            $scope.activeFlag = [false, false, false, false];
            $scope.activeFlag[index] = true;
            $scope.submitted = false;
            switch (index) {
                case 0:
                    initData();
                    break;
                default:
                    break;
            }
        };

        function initData() {
            $scope.markInfo.allCheckedSaleComp = false;
            $scope.markInfo.allCheckedSaleCompRate = false;
            $scope.exportParam.ids = [];
            $scope.saleCompRateIds = [];
            $scope.saleCompIds = [];

        }

        $scope.checkDate = function (obj, startFiled, endFiled) {
            var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
            if (!!timeFormatObj.tStart) {
                obj[startFiled] = timeFormatObj.tStart;
            }
            if (!!timeFormatObj.tEnd) {
                obj[endFiled] = timeFormatObj.tEnd;
            }
        };

        $scope.selectRow = function (index) {
            $scope.markInfo.curRow = index
        };

        $scope.selectAll = function (list, type) {
            angular.forEach(list, function (item) {
                item.isChecked = $scope.markInfo["allChecked" + type];
            });
            switch (type) {
                case 'SaleCompRate':
                    getSaleCompRateIds(list);
                    break;
                case 'SaleComp':
                    getSaleCompIds(list);
                    break;
                default:
                    getBillIds(list);
                    break;
            }

        };

        $scope.selectSingle = function (item, list, type) {
            if (!item.isChecked) {
                $scope.markInfo["allChecked" + type] = false;
            } else {
                if (!checkAll(list)) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    $scope.markInfo["allChecked" + type] = true;
                }
            }

            switch (type) {
                case 'SaleCompRate':
                    getSaleCompRateIds(list);
                    break;
                case 'SaleComp':
                    getSaleCompIds(list);
                    break;
                default:
                    getBillIds(list);
                    break;
            }

        };

        function getBillIds(list) {
            $scope.exportParam.ids = [];
            angular.forEach(list, function (item) {
                if (!!item.isChecked) {
                    $scope.exportParam.ids.push(item.id);
                }
            });
        }

        function getSaleCompRateIds(list) {
            $scope.saleCompRateIds = [];
            angular.forEach(list, function (item) {
                if (!!item.isChecked) {
                    $scope.saleCompRateIds.push(item.id);
                }
            });
        }

        function getSaleCompIds (list) {
            $scope.saleCompIds = [];
            angular.forEach(list, function (item) {
                if (!!item.isChecked) {
                    $scope.saleCompIds.push(item.id);
                }
            });
        }

        function checkAll(list) {
            var selectAll = false;
            for (var i = 0, len = list.length; i < len; i++) {
                if (!list[i].isChecked) {
                    selectAll = false;
                    break;
                }
                selectAll = true;
            }
            return selectAll;
        }

        // 添加价格方案
        $scope.chosePriceScheme = function (item) {
            var param = {
                apiObj: {
                    url: '/marketingActivity/enableList',
                    param: {
                        state: 1
                    }
                }
            };
            ybWidget.PriceSchemeSelector(param).then(function (data) {
                if (!data) return;
                item.activityIdList.push({id: data.id, name: data.name});
            })
        };

        // 主页的评级规则函数集
        $scope.mainRatingRulFunc = {
            search: function (curPage) {
                getRatingList(curPage);
            },
            goAdd: function () {                  // 进入新增页面
                $scope.mainRatingRulObj.detailInfo = {};
                $scope.tabFlag = {
                    name: tabFlag[0],
                    type: 0
                };
                $scope.changeTab(1);
            },
            goEdit: function (item) {             // 进入编辑页面
                $scope.mainRatingRulObj.detailInfo = angular.copy(item);
                $scope.tabFlag = {
                    name: tabFlag[1],
                    type: 1
                };
                $scope.changeTab(1);
            },
            delete: function (item) {             // 删除
                ybWidget.ShowMessage("确认要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteRating([item.id]);
                });
            },
            generateRate: function (ratingId) {           // 生成评分
                generateScore(ratingId).then(function (data) {
                    if (!data) return;
                    getRatingList(1);
                });
            },
            viewRate: function (id) {                     // 查看评分
                if (!id) return;
                $scope.mainRatingRulObj.ratingId = id;
                $scope.viewRateObj.stepList.curStep = 0;
                getScoreList(1);
                $scope.changeTab(9);
            },
            saveData: function (valid) {                  // 保存数据
                if (!valid) {
                    $scope.mainRatingRulObj.submitted = true;
                    return;
                }
                saveRating();
            },
            goMakeRule: function (id) {                   // 制定规则
                if (!id) return;
                $scope.mainRatingRulObj.ratingId = id;
                $scope.changeTab(2);
            },
            goMakeLevel: function (id) {                    // 评级制定
                $scope.levelMakeObj.firstLevel = { activityIdList:[] };
                $scope.levelMakeObj.secondLevel = { activityIdList:[] };
                $scope.levelMakeObj.thirdLevel = { activityIdList:[] };
                $scope.levelMakeObj.fourthLevel = { activityIdList:[] };
                getLevelList(id);
                $scope.mainRatingRulObj.ratingId = id;
                $scope.changeTab(10);
            },
            deletePrice: function (item, index) {
                item.splice(index, 1);
            },
            saveLevelInfo: function () {                    // 保存评级制定信息
                saveLevelInfo().then(function (data) {
                    if (!data) return;
                    $scope.changeTab(0);
                })
            },
            checkLevel: function (curScope, prevScope) {  // 检查名次范围是否合理
                var curStartRank = parseFloat(curScope.startRanking || 0);
                var curEndRank = parseFloat(curScope.endRanking || 0);
                if (curStartRank <= 0) {
                    curScope.err = true;
                    curScope.errMsg = '开始名次不能为空';
                    return;
                }
                if (curEndRank < curStartRank) {
                    curScope.err = true;
                    curScope.errMsg = '结束名次不能小于开始名次';
                    return;
                }
                if (!prevScope || !prevScope.endRanking) {
                    curScope.err = false;
                    return;
                }
                var prevEndRank = parseFloat(prevScope.endRanking);
                if (prevEndRank >= curStartRank) {
                    curScope.err = true;
                    curScope.errMsg = '开始名次不能小于等于上一级的结束名次';
                    return;
                }
                curScope.err = false;
            }
        };

        // 生成评分函数集
        $scope.viewRateFunc = {
            generateRank: function () {           // 生成排名
                generateRank($scope.mainRatingRulObj.ratingId).then(function (data) {
                    if (!data) return;
                    getScoreList(1);
                })
            },
            search: function (curPage) {
                getScoreList(curPage);
            },
            tdClick: function (item, fnType) {      // 表格列点击触发函数
                switch (fnType) {
                    case "editSaleComp":
                        this.editSaleComp(item);
                        break;
                    case "editMonthPlan":
                        this.editMonthPlan(item);
                        break;
                    case "editOrderManage":
                        this.editOrderManage(item);
                        break;
                    case "editReceiveCheck":
                        this.editReceiveCheck(item);
                        break;
                    case "editAllSaleComp":
                        this.editAllSaleComp(item);
                        break;
                    case "editStockAndBusi":
                        this.editStockAndBusi(item);
                        break;
                    default:
                        break;
                }
            },
            editSaleComp: function (item) {             // 编辑销售完成情况
                $scope.viewRateObj.saleCompEditStatus = false;
                getSaleScoreDetail(item.id);
                $scope.viewRateObj.stepList.curStep = 1;
            },
            saveSaleComp: function () {                 // 保存销售完成情况
                var _this = this;
                updateSaleScore().then(function (data) {
                    if (!data) return;
                    getScoreList(1);
                    $scope.viewRateObj.saleCompEditStatus = false;
                    _this.cancel();
                })
            },
            editSaleCompStatus: function () {           // 销售完成情况变成可编辑状态
                $scope.viewRateObj.saleCompEditStatus = true;
            },
            editMonthPlan: function (item) {            // 编辑月度计划准确性
                $scope.viewRateObj.monthEditStatus = false;
                getMonthScoreDetail(item.id);
                $scope.viewRateObj.stepList.curStep = 2;
            },
            saveMonthPlan: function (valid) {                // 保存月度计划准确性
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var _this = this;
                updateMonthScore().then(function (data) {
                    if (!data) return;
                    getScoreList(1);
                    $scope.viewRateObj.monthEditStatus = false;
                    _this.cancel();
                })
            },
            editMonthPlanStatus: function () {
                $scope.viewRateObj.monthEditStatus = true;
            },
            editOrderManage: function (item) {          // 编辑订单管理规范性
                $scope.viewRateObj.orderEditStatus = false;
                getOrderScoreDetail(item.id);
                $scope.viewRateObj.stepList.curStep = 3;
            },
            saveOrderManage: function (valid) {              // 保存订单管理
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var _this = this;
                updateOrderScore().then(function (data) {
                    if (!data) return;
                    getScoreList(1);
                    $scope.viewRateObj.orderEditStatus = false;
                    _this.cancel();
                });
            },
            editOrderManageStatus: function () {
                $scope.viewRateObj.orderEditStatus = true;
            },
            editReceiveCheck: function (item) {         // 编辑应收账款逾期
                $scope.viewRateObj.receiveEditStatus = false;
                getReceiveScoreDetail(item.id);
                $scope.viewRateObj.stepList.curStep = 4;
            },
            saveReceiveCheck: function (valid) {             // 保存应收账款逾期
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var _this = this;
                updateReceiveScore().then(function (data) {
                    if (!data) return;
                    getScoreList(1);
                    $scope.viewRateObj.receiveEditStatus = false;
                    _this.cancel();
                });
            },
            editReceiveStatus: function () {
                $scope.viewRateObj.receiveEditStatus = true;
            },
            editAllSaleComp: function (item) {          // 编辑总体销售完成率
                $scope.viewRateObj.allSaleEditStatus = false;
                getAllSaleDetail(item.id);
                $scope.viewRateObj.stepList.curStep = 5;
            },
            saveAllSaleComp: function (valid) {          // 保存总体销售完成率
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var _this = this;
                updateAllSaleScore().then(function (data) {
                    if (!data) return;
                    getScoreList(1);
                    $scope.viewRateObj.allSaleEditStatus = false;
                    _this.cancel();
                });
            },
            editAllSaleStatus: function () {
                $scope.viewRateObj.allSaleEditStatus = true;
            },
            editStockAndBusi: function (item) {         // 编辑库存管理及业务规范性加减分
                $scope.viewRateObj.stockEditStatus = false;
                getStockDetail(item.id);
                $scope.viewRateObj.stepList.curStep = 6;
            },
            saveStockAndBusi: function (valid) {         // 保存库存管理及业务规范性加减分
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var _this = this;
                updateStockScore().then(function (data) {
                    if (!data) return;
                    getScoreList(1);
                    $scope.viewRateObj.stockEditStatus = false;
                    _this.cancel();
                });
            },
            editStockStatus: function () {
                $scope.viewRateObj.stockEditStatus = true;
            },
            toSort: function (config, index) {
                var sortType = ybWidget.ToSort(config, index);
                var sortField = config[index].sortField;
                var sort = sortField + ' ' + sortType;
                getScoreList($scope.viewRateObj.pageInfo.curPage, sort);
            },
            cancel: function () {                       // 取消
                $scope.submitted = false;
                $scope.viewRateObj.stepList.curStep = 0;
            }
        };

        // 销售完成情况配置函数集
        $scope.saleCompFunc = {
            search: function (curPage) {
                getSaleCompList(curPage);
            },
            goSaleCompList: function () {
                this.cancel();
                getSaleCompList().then(function (data) {
                    if (data) $scope.changeTab(3);
                });
            },
            goTime: function () {            // 配置时间
                $scope.saleCompObj.timeInfo = {};
                var ratingId = $scope.mainRatingRulObj.ratingId;
                var type = TimeConfigTypeEnum.saleComp;
                getRatingTime(ratingId, type).then(function (data) {
                    if (data) {
                        data.value.ratingId = ratingId;
                        data.value.type = type;
                        $scope.saleCompObj.timeInfo = data.value;
                        $scope.saleCompObj.stepList.curStep = 2;
                    }
                });
            },
            saveTime: function (valid) {          // 保存时间配置信息
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var _this = this;
                saveRatingTime($scope.saleCompObj.timeInfo).then(function (data) {
                    if (data) _this.cancel();
                });
            },
            // 新增
            goAdd: function () {
                $scope.saleCompObj.detailInfo = {};
                $scope.saleCompObj.stepList.curStep = 1;
            },
            // 编辑
            goEdit: function (item) {
                $scope.saleCompObj.detailInfo = angular.copy(item);
                $scope.saleCompObj.stepList.curStep = 1;
            },
            // 导入数据
            importData: function () {
                importFile('销售完成情况', UrlObj.saleCompDown, UrlObj.saleCompImp).then(function (data) {
                    data && $scope.saleCompFunc.search(1);
                });
            },
            // 删除
            delete: function (id) {
                ybWidget.ShowMessage("确认要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteSaleComp([id]);
                });
            },

            // 批量删除
            batchDelete: function () {
                ybWidget.ShowMessage("确认要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteSaleComp($scope.saleCompIds);
                });
            },

            // 保存数据
            saveData: function (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                $scope.saleCompObj.detailInfo.ratingId = angular.copy($scope.mainRatingRulObj.ratingId);
                saveSaleComp();
            },
            selectAgent: function () {                       // 选择客户
                selectAgent().then(function (data) {
                    $scope.saleCompObj.detailInfo.clientName = data.companyName;
                    $scope.saleCompObj.detailInfo.clientId = data.id;
                })
            },
            clearAgent: function () {                        // 清除客户
                $scope.saleCompObj.detailInfo.clientName = '';
                $scope.saleCompObj.detailInfo.clientId = '';
            },
            // 取消
            cancel: function () {
                $scope.submitted = false;
                $scope.saleCompObj.stepList.curStep = 0;
            }
        };

        // 月度计划准确性配置函数集
        $scope.monthPlanFunc = {
            goMonthPlan: function () {               // 进入月度计划页面
                $scope.monthPlanObj.timeInfo = {};
                $scope.submitted = false;
                var ratingId = $scope.mainRatingRulObj.ratingId;
                var type = TimeConfigTypeEnum.monthPlan;
                getRatingTime(ratingId, type).then(function (data) {
                    if (!data) return;
                    data.value.ratingId = ratingId;
                    data.value.type = type;
                    $scope.monthPlanObj.timeInfo = data.value;
                    $scope.changeTab(4);
                });
            },
            saveTimeInfo: function (valid) {          // 保存时间配置信息
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                saveRatingTime($scope.monthPlanObj.timeInfo).then(function (data) {
                    if (data) $scope.changeTab(2);
                });
            }
        };

        // 订单管理规范性配置列表函数集
        $scope.orderManageFunc = {
            goOrderManage: function () {              // 进入订单管理页面
                $scope.orderManageObj.timeInfo = {};
                $scope.submitted = false;
                var ratingId = $scope.mainRatingRulObj.ratingId;
                var type = TimeConfigTypeEnum.orderManage;
                getRatingTime(ratingId, type).then(function (data) {
                    if (!data) return;
                    data.value.ratingId = ratingId;
                    data.value.type = type;
                    $scope.orderManageObj.timeInfo = data.value;
                    $scope.changeTab(5);
                });
            },
            saveTimeInfo: function (valid) {           // 保存时间配置信息
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                saveRatingTime($scope.orderManageObj.timeInfo).then(function (data) {
                    if (data) $scope.changeTab(2);
                });
            }
        };

        // 应收账款逾期配置列表函数集
        $scope.receiveCheckFunc = {
            goReceiveCheck: function () {
                this.cancel();
                this.search();
                $scope.changeTab(6);
            },
            // 导入数据
            importData: function () {
                var name = "应收账款逾期";
                var importUrl = UrlObj.receiveCheckImp;
                var downLoadUrl = UrlObj.receiveCheckDown;
                importFile(name, downLoadUrl, importUrl).then(function (data) {
                    data && $scope.receiveCheckFunc.search(1);
                });
            },
            // 搜索列表
            search: function (curPage) {
                getReceiveCheckList(curPage)
            },
            // 编辑
            goEdit: function (item) {
                getReceiveCheckDetail(item.id);
                $scope.receiveCheckObj.stepList.curStep = 1;
            },
            // 删除
            delete: function (id) {
                ybWidget.ShowMessage("确认要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteReceiveCheck([id]);
                });
            },
            // 保存
            saveData: function (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var _this = this;
                saveReceiveCheck().then(function (data) {
                    if (data) {
                        $scope.receiveCheckFunc.search(1);
                        _this.cancel();
                    }
                });
            },
            // 取消
            cancel: function () {
                $scope.submitted = false;
                $scope.receiveCheckObj.stepList.curStep = 0;
            }
        };

        // 总体销售完成率配置函数集
        $scope.allSaleCompFunc = {
            goAllSaleComp: function () {
                this.cancel();
                getAllSaleCompList();
                $scope.changeTab(7);
            },
            search: function (curPage) {
                getAllSaleCompList(curPage);
            },
            goTime: function () {            // 配置时间
                $scope.allSaleCompObj.timeInfo = {};
                var ratingId = $scope.mainRatingRulObj.ratingId;
                var type = TimeConfigTypeEnum.allSaleComp;
                getRatingTime(ratingId, type).then(function (data) {
                    if (data) {
                        data.value.ratingId = ratingId;
                        data.value.type = type;
                        $scope.allSaleCompObj.timeInfo = data.value;
                        $scope.allSaleCompObj.stepList.curStep = 2;
                    }
                });
            },
            saveTime: function (valid) {          // 保存时间配置信息
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var _this = this;
                saveRatingTime($scope.allSaleCompObj.timeInfo).then(function (data) {
                    if (data) _this.cancel();
                });
            },
            // 新增
            goAdd: function () {
                $scope.allSaleCompObj.detailInfo = {};
                $scope.allSaleCompObj.detailInfo.ratingId = $scope.mainRatingRulObj.ratingId;
                $scope.allSaleCompObj.stepList.curStep = 1;
            },
            // 编辑
            goEdit: function (item) {
                $scope.allSaleCompObj.detailInfo = angular.copy(item);
                $scope.allSaleCompObj.stepList.curStep = 1;
            },
            // 导入数据
            importData: function () {
                var name = "总体销售完成率";
                var importUrl = UrlObj.allSaleCompImp;
                var downLoadUrl = UrlObj.allSaleCompDown;
                importFile(name, downLoadUrl, importUrl).then(function (data) {
                    data && getAllSaleCompList(1);
                });
            },
            // 删除
            delete: function (id) {
                ybWidget.ShowMessage("确认要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteAllSaleComp([id]).then(function (data) {
                        if (!data) return;
                        getAllSaleCompList(1);
                    });
                });
            },
            // 删除
            batchDelete: function () {
                ybWidget.ShowMessage("确认要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteAllSaleComp($scope.saleCompRateIds).then(function (data) {
                        if (!data) return;
                        getAllSaleCompList(1);
                    });
                });
            },
            // 保存数据
            saveData: function (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var _this = this;
                saveAllSaleComp().then(function (data) {
                    if (data) {
                        _this.cancel();
                        getAllSaleCompList(1);
                    }
                });
            },
            selectAgent: function () {                       // 选择客户
                selectAgent().then(function (data) {
                    $scope.allSaleCompObj.detailInfo.clientName = data.companyName;
                    $scope.allSaleCompObj.detailInfo.clientId = data.id;
                })
            },
            clearAgent: function () {                        // 清除客户
                $scope.allSaleCompObj.detailInfo.clientName = '';
                $scope.allSaleCompObj.detailInfo.clientId = '';
            },
            // 取消
            cancel: function () {
                $scope.submitted = false;
                $scope.allSaleCompObj.stepList.curStep = 0;
            }
        };

        // 库存管理及业务规范性加减分函数集
        $scope.stockAndBusiFunc = {
            goStockAndBusi: function () {
                this.cancel();
                getStockAndBusiList();
                $scope.changeTab(8);
            },
            search: function (curPage) {
                getStockAndBusiList(curPage);
            },
            // 新增
            goAdd: function () {
                $scope.stockAndBusiObj.detailInfo = {};
                $scope.stockAndBusiObj.detailInfo.ratingId = $scope.mainRatingRulObj.ratingId;
                $scope.stockAndBusiObj.stepList.curStep = 1;
            },
            // 编辑
            goEdit: function (item) {
                $scope.stockAndBusiObj.detailInfo = angular.copy(item);
                $scope.stockAndBusiObj.stepList.curStep = 1;
            },
            // 导入数据
            importData: function () {
                var name = "库存管理及业务规范性加减分";
                var importUrl = UrlObj.stockBusiImp;
                var downLoadUrl = UrlObj.stockBusiDown;
                importFile(name, downLoadUrl, importUrl).then(function (data) {
                    data && getStockAndBusiList(1);
                });
            },
            // 删除
            delete: function (id) {
                ybWidget.ShowMessage("确认要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteStockAndBusi([id]).then(function (data) {
                        if (!data) return;
                        getStockAndBusiList(1);
                    })
                });
            },
            // 保存数据
            saveData: function (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var _this = this;
                saveStockAndBusi().then(function (data) {
                    if (data) {
                        _this.cancel();
                        getStockAndBusiList(1);
                    }
                });
            },
            changeScore: function () {                 // 改变分数
                var stockScore = toNumber(100,$scope.stockAndBusiObj.detailInfo.inaccurateDeduction || 0);
                var businessScore = toNumber(100,$scope.stockAndBusiObj.detailInfo.businessScore || 0);
                $scope.stockAndBusiObj.detailInfo.score = ybWidget.MultiPlus(stockScore, businessScore);
            },
            selectAgent: function () {                       // 选择客户
                selectAgent().then(function (data) {
                    $scope.stockAndBusiObj.detailInfo.clientName = data.companyName;
                    $scope.stockAndBusiObj.detailInfo.clientId = data.id;
                })
            },
            clearAgent: function () {                        // 清除客户
                $scope.stockAndBusiObj.detailInfo.clientName = '';
                $scope.stockAndBusiObj.detailInfo.clientId = '';
            },
            // 取消
            cancel: function () {
                $scope.submitted = false;
                $scope.stockAndBusiObj.stepList.curStep = 0;
            }
        };

        /**
         *  转换数字
         * @param max 最大返回值
         * @param value 要转换的数字
         * @returns number
         */
        function toNumber (max, value) {
            max = Number(max || 0);
            value = Number(value || 0);
            return value > max ? max : value;
        }

        /**
         * 导入公共方法
         * @param name modal 名称
         * @param downloadUrl 下载模板url
         * @param importUrl 导入模板url
         */
        function importFile (name, downloadUrl, importUrl) {
            var param = {
                name: name,
                templateReqService: "device",
                templateReqUrl: downloadUrl,
                importReqService: "device",
                importReqUrl: importUrl,
                ratingId: $scope.mainRatingRulObj.ratingId
            };
            return ybWidget.ImportFile(param).then(function (data) {
                if (data === 'success') return true;
                return false;
            }, function (dismiss) {
                if (dismiss === 'error') return true;
                return false;
            });
        }

        // 选择客户
        function selectAgent () {
            var param = {
                name: "客户",
                type: "commonDealer"
            };
            return ybWidget.SingleSelector(param).then(function (data) {
                return data;
            })
        }

        // 删除对象里的空值
        function delBlankObjKey (obj) {
            if (!obj) return;
            Object.keys(obj).forEach(function (key) {
                if (!obj[key] && obj[key] !== 0) delete obj[key];
            });
        }

        // 获取评级列表
        function getRatingList (curPage) {
            if (angular.isDefined(curPage)) {
                $scope.mainRatingRulObj.pageInfo.curPage = curPage;
            }
            delBlankObjKey($scope.mainRatingRulObj.condition);
            var params = {
                filters: $scope.mainRatingRulObj.condition,
                pageSize: $scope.mainRatingRulObj.pageInfo.pageSize,
                pageNum: $scope.mainRatingRulObj.pageInfo.curPage
            };
            request('ratingList', 'post', params).then(function (data) {
                if (data) {
                    angular.forEach(data.value.list, function (item) {
                        item.isScoreStr = $filter('TrueOrFalse')(item.isScore, 'normal');
                        item.createTimeStr = $filter("YbDate")(item.createTime, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.mainRatingRulObj.pageInfo.totalRows = data.value.total;
                    $scope.mainRatingRulObj.pageInfo.totalPages = data.value.pages;
                    $scope.mainRatingRulObj.dataList = data.value.list;
                }
            })
        }

        // 保存评级管理信息
        function saveRating () {
            var param = $scope.mainRatingRulObj.detailInfo;
            var urlKey = 'ratingAdd';
            if ($scope.tabFlag.type === 1) urlKey = 'ratingUpd';
            request(urlKey, 'post', param).then(function (data) {
                if (data) {
                    ybWidget.ShowToaster('success', '操作成功');
                    getRatingList(1);
                    $scope.changeTab(0);
                }
            })
        }

        // 获取评级管理详情信息
        function getRatingDetail (id) {
            return request('ratingDetail', 'get', {id: id}).then(function (data) {
                if (!data) {
                    return false;
                }
                $scope.mainRatingRulObj.detailInfo = data.value;
                return true;
            })
        }

        // 删除评级管理信息
        function deleteRating (ids) {
            request('ratingDel', 'post', ids).then(function (data) {
                if (data) {
                    ybWidget.ShowToaster('success', '操作成功');
                    getRatingList(1);
                }
            })
        }

        // 获取销售完成情况列表
        function getSaleCompList (curPage) {
            $scope.markInfo.allCheckedSaleComp = false;
            $scope.markInfo.curRow = -1;

            if (angular.isDefined(curPage)) {
                $scope.saleCompObj.pageInfo.curPage = curPage;
            }
            $scope.saleCompObj.condition.ratingId = $scope.mainRatingRulObj.ratingId;
            delBlankObjKey($scope.saleCompObj.condition);
            var params = {
                filters: $scope.saleCompObj.condition,
                pageSize: $scope.saleCompObj.pageInfo.pageSize,
                pageNum: $scope.saleCompObj.pageInfo.curPage
            };
            return request('saleCompList', 'post', params).then(function (data) {
                if (!data) return false;
                angular.forEach(data.value.list, function (item) {
                    item.isChecked = false;
                });
                $scope.saleCompObj.pageInfo.totalRows = data.value.total;
                $scope.saleCompObj.pageInfo.totalPages = data.value.pages;
                $scope.saleCompObj.dataList = data.value.list;
                return true;
            })
        }

        // 新增和更新销售完成情况
        function saveSaleComp () {
            var param = $scope.saleCompObj.detailInfo;
            var urlKey = 'saleCompAdd';
            if (!!param.id) urlKey = 'saleCompUpd';
            request(urlKey, 'post', param).then(function (data) {
                if (data) {
                    ybWidget.ShowToaster('success', '操作成功');
                    getSaleCompList(1);
                    $scope.saleCompFunc.cancel();
                }
            })
        }

        // 删除销售完成情况
        function deleteSaleComp (ids) {
            request('saleCompDel', 'post', ids).then(function (data) {
                if (data) {
                    ybWidget.ShowToaster('success', '操作成功');
                    getSaleCompList(1);
                }
            })
        }

        // 新增或者更新时间配置信息
        function saveRatingTime (obj) {
            var urlKey = 'ratingTimeAdd';
            if (obj.id) urlKey = 'ratingTimeUpd';
            return request(urlKey, 'post', obj).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        /**
         * 获取时间配置信息
         * @param ratingId 评级管理主表的id
         * @param type 规则类型
         * @returns {*}
         */
        function getRatingTime (ratingId, type) {
            var params = {
                ratingId: ratingId,
                type: type
            };
            return request('getRatingTime', 'get', params).then(function (data) {
                if (!data) return false;
                if (!data.value) return data;
                if (data.value.startTime) {
                    data.value.startTime = $filter("YbDate")(data.value.startTime);
                }
                if (data.value.endTime) {
                    data.value.endTime = $filter("YbDate")(data.value.endTime);
                }
                return data;
            })
        }

        // 获取应收账款逾期列表
        function getReceiveCheckList (curPage) {
            if (angular.isDefined(curPage)) {
                $scope.receiveCheckObj.pageInfo.curPage = curPage;
            }
            $scope.receiveCheckObj.condition.ratingId = $scope.mainRatingRulObj.ratingId;
            delBlankObjKey($scope.receiveCheckObj.condition);
            var params = {
                filters: $scope.receiveCheckObj.condition,
                pageSize: $scope.receiveCheckObj.pageInfo.pageSize,
                pageNum: $scope.receiveCheckObj.pageInfo.curPage
            };
            return request('receiveCheckList', 'post', params).then(function (data) {
                if (!data) return false;
                $scope.receiveCheckObj.pageInfo.totalRows = data.value.total;
                $scope.receiveCheckObj.pageInfo.totalPages = data.value.pages;
                $scope.receiveCheckObj.dataList = data.value.list;
                return true;
            })
        }

        // 删除应收账款逾期
        function deleteReceiveCheck (ids) {
            request('receiveCheckDel', 'post', ids).then(function (data) {
                if (data) {
                    ybWidget.ShowToaster('success', '操作成功');
                    getReceiveCheckList(1);
                }
            })
        }

        // 获取详情
        function getReceiveCheckDetail (id) {
            request('receiveCheckItem', 'get', {id: id}).then(function (data) {
                if (!data) {
                    return false;
                }
                $scope.receiveCheckObj.detailInfo = data.value;
                return true;
            })
        }

        // 保存应收账款逾期
        function saveReceiveCheck () {
            var param = $scope.receiveCheckObj.detailInfo;
            return request('receiveCheckUpd', 'post', param).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 获取总体销售情况配置列表
        function getAllSaleCompList (curPage) {
            $scope.markInfo.allCheckedSaleCompRate = false;
            $scope.markInfo.curRow = -1;

            if (angular.isDefined(curPage)) {
                $scope.allSaleCompObj.pageInfo.curPage = curPage;
            }
            $scope.allSaleCompObj.condition.ratingId = $scope.mainRatingRulObj.ratingId;
            delBlankObjKey($scope.allSaleCompObj.condition);
            var params = {
                filters: $scope.allSaleCompObj.condition,
                pageSize: $scope.allSaleCompObj.pageInfo.pageSize,
                pageNum: $scope.allSaleCompObj.pageInfo.curPage
            };
            return request('allSaleCompList', 'post', params).then(function (data) {
                if (!data) return false;
                angular.forEach(data.value.list, function (item) {
                    item.isChecked = false;
                });
                $scope.allSaleCompObj.pageInfo.totalRows = data.value.total;
                $scope.allSaleCompObj.pageInfo.totalPages = data.value.pages;
                $scope.allSaleCompObj.dataList = data.value.list;
                return true;
            })
        }

        // 保存总体销售情况配置
        function saveAllSaleComp () {
            var params = angular.copy($scope.allSaleCompObj.detailInfo);
            var urlKey = 'allSaleCompAdd';
            if (params.id) urlKey = 'allSaleCompUpd';
            return request(urlKey, 'post', params).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 删除总体销售情况配置
        function deleteAllSaleComp (ids) {
            return request('allSaleCompDel', 'post', ids).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 获取库存管理及业务规范列表
        function getStockAndBusiList (curPage) {
            if (angular.isDefined(curPage)) {
                $scope.stockAndBusiObj.pageInfo.curPage = curPage;
            }
            $scope.stockAndBusiObj.condition.ratingId = $scope.mainRatingRulObj.ratingId;
            delBlankObjKey($scope.stockAndBusiObj.condition);
            var params = {
                filters: $scope.stockAndBusiObj.condition,
                pageSize: $scope.stockAndBusiObj.pageInfo.pageSize,
                pageNum: $scope.stockAndBusiObj.pageInfo.curPage
            };
            return request('stockBusiList', 'post', params).then(function (data) {
                if (!data) return false;
                $scope.stockAndBusiObj.pageInfo.totalRows = data.value.total;
                $scope.stockAndBusiObj.pageInfo.totalPages = data.value.pages;
                $scope.stockAndBusiObj.dataList = data.value.list;
                return true;
            })
        }

        // 删除库存管理及业务规范
        function deleteStockAndBusi(ids) {
            return request('stockBusiDel', 'post', ids).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 保存库存管理及业务规范
        function saveStockAndBusi () {
            var params = angular.copy($scope.stockAndBusiObj.detailInfo);
            var urlKey = 'stockBusiAdd';
            if (params.id) urlKey = 'stockBusiUpd';
            return request(urlKey, 'post', params).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 获取评分列表
        function getScoreList (curPage, sort) {
            if (angular.isDefined(curPage)) {
                $scope.viewRateObj.pageInfo.curPage = curPage;
            }
            $scope.viewRateObj.condition.ratingId = $scope.mainRatingRulObj.ratingId;
            delBlankObjKey($scope.viewRateObj.condition);
            var params = {
                filters: $scope.viewRateObj.condition,
                pageSize: $scope.viewRateObj.pageInfo.pageSize,
                pageNum: $scope.viewRateObj.pageInfo.curPage
            };
            if (sort) params.sort = sort;
            return request('scoreList', 'post', params).then(function (data) {
                if (!data) return false;
                $scope.viewRateObj.pageInfo.totalRows = data.value.total;
                $scope.viewRateObj.pageInfo.totalPages = data.value.pages;
                $scope.viewRateObj.dataList = data.value.list;
                return true;
            })
        }

        // 生成排名
        function generateRank (ratingId) {
            return request('generateRank', 'get', {ratingId: ratingId}).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 生成评分
        function generateScore (ratingId) {
            var url = UrlObj.generateScore;
            return ybHttp.Get('device', url, {ratingId: ratingId}).then(function (res) {
                if (res.code !== 0) {
                    ybWidget.ShowMessage(res, MESG_TYPE.Error);
                    return false;
                }
                if (res.value) {
                    // 让错误信息换行展示
                    res.value = res.value.split(',').join('\<br\>');
                    ybWidget.ShowMessage(res.value, MESG_TYPE.Warn, { isHtml: true });
                    return true;
                }
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 获取销售完成情况得分详情
        function getSaleScoreDetail (scoreInfoId) {
            return request('scoreSaleItem', 'get', {scoreInfoId: scoreInfoId}).then(function (data) {
                if (!data) return false;
                if (!data.value) data.value = {};
                data.value.scoreInfoId = scoreInfoId;
                $scope.viewRateObj.saleCompDetail = data.value;
                return true;
            });
        }

        // 更新销售完成情况得分详情
        function updateSaleScore () {
            var params = $scope.viewRateObj.saleCompDetail;
            return request('scoreSaleUpd', 'post', params).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 获取月度计划得分详情
        function getMonthScoreDetail (scoreInfoId) {
            return request('scoreMonthItem', 'get', {scoreInfoId: scoreInfoId}).then(function (data) {
                if (!data) return false;
                if (!data.value) data.value = {};
                data.value.scoreInfoId = scoreInfoId;
                $scope.viewRateObj.monthPlanDetail = data.value;
                return true;
            });
        }

        // 更新月度计划得分详情
        function updateMonthScore () {
            var params = $scope.viewRateObj.monthPlanDetail;
            return request('scoreMonthUpd', 'post', params).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 获取月度计划得分详情
        function getOrderScoreDetail (scoreInfoId) {
            return request('scoreOrderItem', 'get', {scoreInfoId: scoreInfoId}).then(function (data) {
                if (!data) return false;
                if (!data.value) data.value = {};
                data.value.scoreInfoId = scoreInfoId;
                $scope.viewRateObj.orderManageDetail = data.value;
                return true;
            });
        }

        // 更新月度计划得分详情
        function updateOrderScore () {
            var params = $scope.viewRateObj.orderManageDetail;
            return request('scoreOrderUpd', 'post', params).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 获取应收账款逾期得分详情
        function getReceiveScoreDetail (scoreInfoId) {
            return request('scoreReceiveItem', 'get', {scoreInfoId: scoreInfoId}).then(function (data) {
                if (!data) return false;
                if (!data.value) data.value = {};
                data.value.scoreInfoId = scoreInfoId;
                $scope.viewRateObj.receiveDetail = data.value;
                return true;
            });
        }

        // 更新应收账款逾期得分详情
        function updateReceiveScore () {
            var params = $scope.viewRateObj.receiveDetail;
            return request('scoreReceiveUpd', 'post', params).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 获取总体销售完成率得分详情
        function getAllSaleDetail (scoreInfoId) {
            return request('scoreAllSaleItem', 'get', {scoreInfoId: scoreInfoId}).then(function (data) {
                if (!data) return false;
                if (!data.value) data.value = {};
                data.value.scoreInfoId = scoreInfoId;
                $scope.viewRateObj.allSaleDetail = data.value;
                return true;
            });
        }

        // 更新总体销售完成率得分详情
        function updateAllSaleScore () {
            var params = $scope.viewRateObj.allSaleDetail;
            return request('scoreAllSaleUpd', 'post', params).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 获取库存管理及业务规范得分详情
        function getStockDetail (scoreInfoId) {
            return request('scoreStockItem', 'get', {scoreInfoId: scoreInfoId}).then(function (data) {
                if (!data) return false;
                if (!data.value) data.value = {};
                data.value.scoreInfoId = scoreInfoId;
                $scope.viewRateObj.stockDetail = data.value;
                return true;
            });
        }

        // 更新库存管理及业务规范得分详情
        function updateStockScore () {
            var params = $scope.viewRateObj.stockDetail;
            return request('scoreStockUpd', 'post', params).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 保存等级制定信息
        function saveLevelInfo () {
            var urlKey = 'levelUpd';
            var firstLevel = angular.copy($scope.levelMakeObj.firstLevel);
            firstLevel.level = 's';
            var secondLevel = angular.copy($scope.levelMakeObj.secondLevel);
            secondLevel.level = 'a';
            var thirdLevel = angular.copy($scope.levelMakeObj.thirdLevel);
            thirdLevel.level = 'b';
            var fourthLevel = angular.copy($scope.levelMakeObj.fourthLevel);
            fourthLevel.level = 'c';
            if (firstLevel.err || secondLevel.err || thirdLevel.err || fourthLevel.err) {
                var deferred = $q.defer();
                deferred.resolve(false);
                return deferred.promise;
            }
            var param = {
                ratingId: $scope.mainRatingRulObj.ratingId,
                marketingDealerList: [firstLevel, secondLevel, thirdLevel, fourthLevel],
            };
            return request(urlKey, 'post', param).then(function (data) {
                if (!data) return false;
                ybWidget.ShowToaster('success', '操作成功');
                return true;
            })
        }

        // 获取等级制定列表
        function getLevelList (ratingId) {
            return request('levelList', 'get', {ratingId: ratingId}).then(function (data) {
                if (!data) return false;
                angular.forEach(data.value, function (item) {
                    if (item.level.toLowerCase() === 's') {
                        $scope.levelMakeObj.firstLevel = item;
                    }
                    if (item.level.toLowerCase() === 'a') {
                        $scope.levelMakeObj.secondLevel = item;
                    }
                    if (item.level.toLowerCase() === 'b') {
                        $scope.levelMakeObj.thirdLevel = item;
                    }
                    if (item.level.toLowerCase() === 'c') {
                        $scope.levelMakeObj.fourthLevel = item;
                    }
                });
                return true;
            })
        }

        // 请求url对象
        var UrlObj = {
            ratingAdd: '/ratingInfo/add',                                            // 新增评级管理主信息
            ratingDel: '/ratingInfo/delete',                                         // 删除评级信息
            ratingDetail: '/ratingInfo/item',                                        // 获取评级详情
            ratingList: '/ratingInfo/list',                                          // 获取评级列表
            ratingUpd: '/ratingInfo/update',                                         // 修改评级管理主信息
            getRatingTime: '/ratingConfigTime/item',                                 // 获取时间配置信息
            ratingTimeAdd: '/ratingConfigTime/add',                                  // 新增时间配置信息
            ratingTimeUpd: '/ratingConfigTime/update',                               // 更新时间配置信息
            saleCompDown: '/salesCompleteConfig/download',                           // 销售完成情况下载模板
            saleCompImp: '/salesCompleteConfig/import',                              // 销售完成情况导入
            saleCompAdd: '/salesCompleteConfig/add',                                 // 销售完成情况新增
            saleCompDel: '/salesCompleteConfig/delete',                              // 销售完成情况删除
            saleCompItem: '/salesCompleteConfig/item',                               // 销售完成情况详情
            saleCompList: '/salesCompleteConfig/list',                               // 销售完成情况列表
            saleCompUpd: '/salesCompleteConfig/update',                              // 销售完成情况更新
            receiveCheckDown: '/accountOverdueConfig/download',                      // 应收账款逾期下载模板
            receiveCheckImp: '/accountOverdueConfig/import',                         // 应收账款逾期导入
            receiveCheckDel: '/accountOverdueConfig/delete',                         // 应收账款逾期删除
            receiveCheckItem: '/accountOverdueConfig/item',                          // 应收账款逾期详情
            receiveCheckList: '/accountOverdueConfig/list',                          // 应收账款逾期列表
            receiveCheckUpd: '/accountOverdueConfig/update',                         // 应收账款逾期更新
            allSaleCompAdd: '/completeRateConfig/add',                               // 总销售完成情况新增
            allSaleCompDel: '/completeRateConfig/delete',                            // 总销售完成情况删除
            allSaleCompDown: '/completeRateConfig/download',                         // 总销售完成情况下载模板
            allSaleCompImp: '/completeRateConfig/import',                            // 总销售完成情况导入
            allSaleCompItem: '/completeRateConfig/item',                             // 总销售完成情况详情
            allSaleCompList: '/completeRateConfig/list',                             // 总销售完成情况列表
            allSaleCompUpd: '/completeRateConfig/update',                            // 总销售完成情况更新
            stockBusiAdd: '/inventoryBusinessConfig/add',                            // 库存管理及业务规范新增
            stockBusiDel: '/inventoryBusinessConfig/delete',                         // 库存管理及业务规范删除
            stockBusiDown: '/inventoryBusinessConfig/download',                      // 库存管理及业务规范下载模板
            stockBusiImp: '/inventoryBusinessConfig/import',                         // 库存管理及业务规范导入
            stockBusiItem: '/inventoryBusinessConfig/item',                          // 库存管理及业务规范详情
            stockBusiList: '/inventoryBusinessConfig/list',                          // 库存管理及业务规范列表
            stockBusiUpd: '/inventoryBusinessConfig/update',                         // 库存管理及业务规范更新
            generateRank: '/scoreInfo/generateRanking',                              // 查看评分生成排名
            generateScore: '/scoreInfo/generateRating',                              // 查看评分生成评分
            scoreList: '/scoreInfo/list',                                            // 查看评分列表
            scoreMonthItem: '/scoreInfoDetail/getMonthPlanAccuracyDetail',           // 月度计划评分详情
            scoreMonthUpd: '/scoreInfoDetail/updateMonthPlanAccuracyDetail',         // 月度计划评分更新
            scoreOrderItem: '/scoreInfoDetail/getOrderNormativeDetail',              // 订单管理规范性评分详情
            scoreOrderUpd: '/scoreInfoDetail/updateOrderNormativeDetail',            // 订单管理规范性评分更新
            scoreAllSaleItem: '/scoreInfoDetail/getOverallCompleteDetail',           // 总体销售完成率评分详情
            scoreAllSaleUpd: '/scoreInfoDetail/updateOverallCompleteDetail',         // 总体销售完成率评分更新
            scoreReceiveItem: '/scoreInfoDetail/getReceivableOverdueDetail',         // 应收账款逾期评分详情
            scoreReceiveUpd: '/scoreInfoDetail/updateReceivableOverdueDetail',       // 应收账款逾期评分更新
            scoreSaleItem: '/scoreInfoDetail/getSalesCompleteDetail',                // 销售情况评分详情
            scoreSaleUpd: '/scoreInfoDetail/updateSalesCompleteDetail',              // 销售情况评分更新
            scoreStockItem: '/scoreInfoDetail/getStockBusinessDetail',               // 库存管理及业务规范性评分详情
            scoreStockUpd: '/scoreInfoDetail/updateStockBusinessDetail',             // 库存管理及业务规范性评分更新
            levelUpd: '/marketDealerRating/update',                                  // 等级制定更新
            levelList: '/marketDealerRating/list',                                   // 等级制定列表
        };

        //请求类型对象
        var RequestTypeObj = {
            get: 'Get',
            post: 'Post'
        };

        /**
         * 公共请求方法
         * @param urlKey 请求url的UrlObj对象的键值
         * @param type 请求类型RequestTypeObj对象的键值
         * @param param 请求的参数
         */
        function request (urlKey, type, param) {
            var url = UrlObj[urlKey];
            var method = RequestTypeObj[type];
            if (!url || !method) return false;
            return ybHttp[method]('device', url, param).then(function (res) {
                if (res.code !== 0) {
                    ybWidget.ShowMessage(res, MESG_TYPE.Error);
                    return false;
                }
                return res;
            });
        }

        (function () {
            UserContextService.SetBtnPermission(setBtnPermission);
            $scope.setFixedWidth();
            getRatingList();
        })();
    }])
})(window, window.angular);